package com.sx.pipeline.ui.linepipe.file

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.Settings
import android.text.TextUtils
import android.view.View
import android.widget.EditText
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.ToastUtils
import com.blankj.utilcode.util.UriUtils
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.lxj.xpopup.interfaces.OnConfirmListener
import com.sx.mvvmlibs.binding.edittext.viewAdapter
import com.sx.mvvmlibs.utils.Logs
import com.sx.pipeline.BR
import com.sx.pipeline.R
import com.sx.pipeline.app.base.CYBaseAppBarActivity
import com.sx.pipeline.arouth.RoutePath
import com.sx.pipeline.databinding.ActImportFilesBinding
import com.sx.pipeline.ui.linepipe.LinePipeVM
import java.io.File


/**
 * @Author: YY
 * @Date: 2022/4/5
 * @Description: 我的管线 - 导入文件
 */
@Route(path = RoutePath.LinePipe.LINE_PIPE_FILE)
class LinePipeFilesActivity : CYBaseAppBarActivity<ActImportFilesBinding, LinePipeFilesVM>
    (R.layout.act_import_files), View.OnClickListener {

    private lateinit var mPopup: BasePopupView

    private var fileName: String = ""
    private var fileType: Int = 0

    override fun initAppBar() {
        getTitleBar().title = "导入我的管线"
    }

    override fun initData() {
        mBinding.setVariable(BR.onClick, this)
        mBinding.tvTipLine.visibility = View.VISIBLE
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.tv_confirm -> {
                if (!TextUtils.isEmpty(fileName)) {
                    showInputDialog()
                } else {
                    ToastUtils.showShort("请输入文件名称")
                }
            }
            R.id.ll_import -> {
                requestPermission()
            }
        }
    }

    private val REQUEST_CODE = 1024
    private fun requestPermission() {
        if (Build.VERSION.SDK_INT >= 30) {
            // 先判断有没有权限
            if (Environment.isExternalStorageManager()) {
                openFileManager()
            } else {
                val intent = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION)
                intent.data = Uri.parse("package:" + application.packageName)
                startActivityForResult(intent, REQUEST_CODE)
            }
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // 先判断有没有权限
            if (ActivityCompat.checkSelfPermission(
                    this,
                    Manifest.permission.READ_EXTERNAL_STORAGE
                ) == PackageManager.PERMISSION_GRANTED &&
                ContextCompat.checkSelfPermission(
                    this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                ) == PackageManager.PERMISSION_GRANTED
            ) {
                openFileManager()
            } else {
                ActivityCompat.requestPermissions(
                    this,
                    arrayOf(
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                    ),
                    REQUEST_CODE
                )
            }
        } else {
            openFileManager()
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == REQUEST_CODE) {
            if (ActivityCompat.checkSelfPermission(
                    this,
                    Manifest.permission.READ_EXTERNAL_STORAGE
                ) == PackageManager.PERMISSION_GRANTED &&
                ContextCompat.checkSelfPermission(
                    this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                ) == PackageManager.PERMISSION_GRANTED
            ) {
                openFileManager()
            } else {
                Toast.makeText(this, "存储权限获取失败", Toast.LENGTH_LONG).show()
            }
        }
    }


    override fun initViewObservable() {
        super.initViewObservable()
        // kml文件数据
        observe(mViewModel.fileTypeEvent) { data ->
            if (data!!) {
                mBinding.tvImport.visibility = View.GONE
                mBinding.imageFile.visibility = View.VISIBLE
            } else {
                mBinding.tvImport.visibility = View.GONE
                mBinding.imageFile.setImageDrawable(getDrawable(R.drawable.ic_dxf_file))
                mBinding.imageFile.visibility = View.VISIBLE
            }
        }
    }

    @Deprecated("Deprecated in Java")
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        Logs.d("onActivityResult $resultCode")
        if (resultCode != RESULT_OK) {
            return
        } else if (requestCode == 1000) {
            if (data != null) {
                val uri: Uri = data.data!!
                val file: File = UriUtils.uri2File(uri)
                if (file.name.endsWith(".kml")) {
                    fileName = file.name
                    fileType = 0
                    mViewModel.kmlAnalysis(file)
                } else if(file.name.endsWith(".dxf")) {
                    fileName = file.name
                    fileType = 1
                    mViewModel.dxfAnalysis(file)

                } else {
                    mBinding.tvImport.visibility = View.VISIBLE
                    mBinding.imageFile.visibility = View.GONE
                    ToastUtils.showShort("文件格式错误，请重新导入")
                }
            }
        }
    }

    private fun openFileManager() {
        // 打开文件管理器选择文件
        val intent = Intent(Intent.ACTION_GET_CONTENT)
        // 类型限制
        intent.type = "*/*"
        intent.addCategory(Intent.CATEGORY_OPENABLE)
        startActivityForResult(intent, 1000)
    }

    /**
     * 输入名称
     */
    private fun showInputDialog() {
        mPopup = XPopup.Builder(this)
            .autoDismiss(false)
            .asInputConfirm("请输入文件名称",
                "", fileName, "文件名称") {
                if (!TextUtils.isEmpty(it)) {
                    mViewModel.saveFileBean(it, fileType)
                    mPopup.dismiss()
                } else {
                    ToastUtils.showShort("请输入文件名称")
                }
            }.also {
                val editText = it.findViewById<EditText>(com.lxj.xpopup.R.id.et_input)
                viewAdapter.filterEditText(editText, true)
            }.show()
    }
}